package mirkofrancuski.battleship.db;

import java.util.HashMap;
import java.util.Iterator;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class IntTable {
	private static final String INT_TABLE = "Int_table";
	private static final String INT_CLASS = "Class";
	private static final String INT_NAME = "Name";
	private static final String INT_VALUE = "Value";

	private static final String CREATE_INT_TABLE = "CREATE TABLE " + INT_TABLE
			+ " (" + INT_CLASS + " TEXT, " + INT_NAME + " TEXT, " + INT_VALUE
			+ " INTEGER" + ")";

	public static void onCreate(SQLiteDatabase database) {
		database.execSQL(CREATE_INT_TABLE);
	}

	public static void onUpgrade(SQLiteDatabase database, int oldVersion,
			int newVersion) {
		Log.w(HighScoreTable.class.getName(),
				"Upgrading database from version " + oldVersion + " to "
						+ newVersion + ", which will destroy all old data");
		database.execSQL("DROP TABLE IF EXISTS " + CREATE_INT_TABLE);
		onCreate(database);
	}

	public static void addInt(SQLiteDatabase db, String className, String name,
			int value) {

		ContentValues cv = new ContentValues();
		cv.put(INT_CLASS, className);
		cv.put(INT_NAME, name);
		cv.put(INT_VALUE, value);

		db.insert(INT_TABLE, null, cv);
	}

	public static HashMap<String, Integer> getInts(SQLiteDatabase db,
			String className) {
		HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
		String selectQuery = "SELECT " + INT_NAME + ", " + INT_VALUE + " FROM "
				+ INT_TABLE + " WHERE " + INT_CLASS + " = " + className;
		Cursor cursor = null;

		try {
			cursor = db.rawQuery(selectQuery, null);

			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
					.moveToNext()) {
				String name = cursor.getString(0); // variable name
				int value = Integer.parseInt(cursor.getString(1));

				hashMap.put(name, value);
			}
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return hashMap;
	}

	public static void deleteAllInts(SQLiteDatabase db, String className) {
		db.delete(INT_TABLE, INT_CLASS + " = ?", new String[] { className });
	}
}
